package com.flow.framework.core.system.thread.pool.task;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 基础线程池任务
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/23
 */
@Slf4j
public abstract class BaseRunnable extends BaseTask implements Runnable {

    /**
     * 创建任务
     *
     * @param timeout 任务超时时间
     */
    public BaseRunnable(long timeout) {
        super(timeout);
    }

    /**
     * @inheritDoc
     */
    @Override
    public final void run() {
        try {
            preprocess();
            execute();
        } catch (Throwable throwable) {

            // 不抛出异常，避免线程终止被回收重新创建线程
            log.error("execute error.", throwable);
        } finally {
            try {
                postprocess();
            } catch (Throwable throwable) {

                // 不抛出异常，避免线程终止被回收重新创建线程
                log.error("execute postprocess error.", throwable);
            }
        }
    }

    /**
     * @inheritDoc
     */
    @Override
    public final Map<String, String> getMdcContext() {
        return super.getMdcContext();
    }

    /**
     * 执行任务的方法体
     */
    protected abstract void execute();

    /**
     * @inheritDoc
     */
    @Override
    public final long getTimeout() {
        return super.getTimeout();
    }
}
